package com.diary;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtils {          //工具类

    private static String driverClass;
    private static String url;
    private static String user;
    private static String password;

    static {        //静态代码块，随着类的加载而加载，只执行一次
        InputStream resourceAsStream = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");      //通过流加载信息

        Properties properties = new Properties();

        try {
            properties.load(resourceAsStream);          //加载流的信息

            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");

            Class.forName(driverClass);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection()  throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }

    public static void close(ResultSet resultSet, Statement statement,Connection connection) {        //statement是父类，尽量用父类接口或者抽象类
        //因为有很多重复代码，所以调用这个就可以减少代码量

        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        try {
            if (statement != null){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}





















